﻿using Paperless.Entities;
using Paperless.Models;
using Paperless.Repositories;
using System.Web.Http;
using System.Linq;
using System.Collections.Generic;
using AutoMapper;
using System.Threading.Tasks;
using System;
using Microsoft.AspNet.Identity;

namespace Paperless.Controllers
{
    [Route("api/transaction/{transactionId}/contact/{id?}")]
    public class ContactController : ApiController
    {
        public IRepository<Contact> Repository { get; set; }

        public ContactController(IRepository<Contact> repository)
        {
            Repository = repository;
        }

        public IHttpActionResult GetByTransactionId(long transactionId)
        {
            var entities = Repository.DbSet().Where(x => x.TransactionId == transactionId)
                .OrderBy(x => x.CreatedDate);

            var model = Mapper.Map<IEnumerable<ContactModel>>(entities);

            return Ok(model);
        }

        public async Task<IHttpActionResult> Post(ContactModel model, long transactionId)
        {
            model.CreatedBy = User.Identity.GetUserName();
            model.CreatedDate = DateTime.Now;
            model.TransactionId = transactionId;

            var entity = Mapper.Map<Contact>(model);

            try
            {
                await Repository.Add(entity);
            }
            catch (Exception e)
            {
                return InternalServerError(e);
            }

            return Ok(entity.Id);
        }

        public async Task<IHttpActionResult> Put(ContactModel model)
        {
            model.UpdatedBy = User.Identity.GetUserName();
            model.UpdatedDate = DateTime.Now;

            var entity = Mapper.Map<Contact>(model);

            try
            {
                await Repository.Update(entity);
            }
            catch (Exception e)
            {
                return InternalServerError(e);
            }

            return Ok();
        }

        public async Task<IHttpActionResult> Delete(long id)
        {
            try
            {
                await Repository.Remove(id);
            }
            catch (Exception e)
            {
                return InternalServerError(e);
            }

            return Ok();
        }
    }
}